﻿using ComprehensiveSystem.Configuration;
using ComprehensiveSystem.IRepository;
using ComprehensiveSystem.IRepository.UnitOfWork;
using ComprehensiveSystem.IServices;
using ComprehensiveSystem.Model.Entities;
using ComprehensiveSystem.Model.Entities.Expression;
using ComprehensiveSystem.Model.ViewModels.Basics;
using ComprehensiveSystem.Model.ViewModels.UI;
using ComprehensiveSystem.Services.Services;
using ComprehensiveSystem.Utility.Extensions;
using CoreCms.Net.Middlewares;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.Linq.Expressions;

namespace ComprehensiveSystem.Services
{

    public class PatientEntityServices : BaseServices<PatientEntity>, IPatientServices
    {
        private readonly IPatientRepository _dal;
        private readonly IUnitOfWork _unitOfWork;

        public PatientEntityServices(IUnitOfWork unitOfWork, IPatientRepository dal)
        {
            this._dal = dal;
            base.BaseDal = dal;
            _unitOfWork = unitOfWork;
        }

        #region 实现重写增删改查操作==========================================================

        /// <summary>
        /// 重写异步插入方法
        /// </summary>
        /// <param name="entity">实体数据</param>
        /// <returns></returns>
        public new async Task<WebApiCallBack> InsertAsync(PatientEntity entity)
        {
            //entity.Create();
            //var jm = await _dal.InsertAsync(entity);
            //return jm;

            WebApiCallBack jm = new WebApiCallBack();
            
            entity.Create();
            var bl = await _dal.InsertAsyncEx(entity);

            jm.status = (bl != null ? true : false);
            jm.code = (bl != null ? 0 : 1);
            jm.data = bl;
            jm.msg = jm.status ? GlobalConstVars.CreateSuccess : GlobalConstVars.CreateFailure;
            if (jm.status)
            {
                //await UpdateCaChe();
            }

            return jm;
        }

        /// <summary>
        /// 重写异步更新方法方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public new async Task<WebApiCallBack> UpdateAsync(PatientEntity entity)
        {
            //entity.Modify();
            //var jm = await _dal.UpdateAsync(entity);
            //return jm;

            var jm = new WebApiCallBack();

            var oldModel = await _dal.QueryByIdAsync(entity.Id);
            if (entity.Id.IsNullOrZero())
            {
                throw new BusinessException("数据标识丢失！");
            }
            if (oldModel == null || (oldModel != null && oldModel.DeleteMark == 1))
            {
                throw new BusinessException("该数据不存在或已被删除,请稍后重试！");
            }

            //事物处理过程开始

            //oldModel.Id = entity.Id;

            //oldModel.createTime = entity.createTime;

            //oldModel.lastModifyTime = entity.lastModifyTime;

            //oldModel.deleteTime = entity.deleteTime;

            //oldModel.DeleteMark = entity.DeleteMark;

            //oldModel.createUserId = entity.createUserId;

            //oldModel.lastModifyUserId = entity.lastModifyUserId;

            //oldModel.deleteUserId = entity.deleteUserId;

            //事物处理过程结束

            oldModel.PathCodeMark = entity.PathCodeMark;
            oldModel.CheckPathCode = entity.CheckPathCode;
            oldModel.ICUDay = entity.ICUDay;
            oldModel.LiveDay = entity.LiveDay;
            oldModel.PathCode = entity.PathCode;
            oldModel.StartToEndJson = entity.StartToEndJson;

            oldModel.Modify();

            var bl = await _dal.UpdateAsync(oldModel);
            jm.status = bl;
            jm.code = bl ? 0 : 1;
            jm.data = oldModel;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;
            if (bl)
            {
                //await UpdateCaChe();
            }

            return jm;
        }

        /// <summary>
        /// 重写异步更新方法方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public new async Task<WebApiCallBack> UpdateAsync(List<PatientEntity> entity)
        {
            //return await _dal.UpdateAsync(entity);

            var jm = new WebApiCallBack();
            entity.ForEach(p => p.Modify());
            var bl = await _dal.UpdateAsync(entity);
            jm.status = bl;
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;
            if (bl)
            {
                //await UpdateCaChe();
            }

            return jm;
        }

        /// <summary>
        /// 重写删除指定ID的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public new async Task<WebApiCallBack> DeleteByIdAsync(object id)
        {
            //return await _dal.DeleteByIdAsync(Id);

            var jm = new WebApiCallBack();
            if (id.IsNullOrZero())
            {
                throw new BusinessException("数据标识丢失！");
            }
            var Model = await _dal.QueryByIdAsync(id);
            if (Model == null || (Model != null && Model.DeleteMark == 1))
            {
                throw new BusinessException("不存在此信息,请刷新页面后重试！");
            }
            var bl = await _dal.DeleteByIdAsync(id);
            jm.status = bl;
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.DeleteSuccess : GlobalConstVars.DeleteFailure;
            if (bl)
            {
                //await UpdateCaChe();
            }

            return jm;
        }

        /// <summary>
        /// 重写删除指定ID的数据(伪删除)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<WebApiCallBack> DeleteMarkByIdAsync(object id)
        {
            //var jm = await _dal.DeleteMarkByIdAsync(Id);
            //return jm;

            var jm = new WebApiCallBack();
            if (id.IsNullOrZero())
            {
                throw new BusinessException("数据标识丢失！");
            }
            var Model = await _dal.QueryByIdAsync(id);
            if (Model == null || (Model != null && Model.DeleteMark == 1))
            {
                throw new BusinessException("不存在此信息,请刷新页面后重试！");
            }

            Model.Remove();
            var bl = await _dal.UpdateAsync(Model);
            jm.status = bl;
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.DeleteSuccess : GlobalConstVars.DeleteFailure;
            if (bl)
            {
                //await UpdateCaChe();
            }

            return jm;
        }

        /// <summary>
        /// 重写删除指定ID集合的数据(批量删除)
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public new async Task<WebApiCallBack> DeleteByIdsAsync(string[] ids)
        {
            //return await _dal.DeleteByIdsAsync(ids);

            var jm = new WebApiCallBack();

            var bl = await _dal.DeleteByIdsAsync(ids);
            jm.status = bl;
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.DeleteSuccess : GlobalConstVars.DeleteFailure;
            if (bl)
            {
                //await UpdateCaChe();
            }

            return jm;
        }

        #endregion

        #region 获取缓存的所有数据==========================================================

        /// <summary>
        /// 获取缓存的所有数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<PatientEntity>> GetCaChe()
        {
            return await _dal.GetCaChe();
        }

        /// <summary>
        ///     更新cache
        /// </summary>
        public async Task<List<PatientEntity>> UpdateCaChe()
        {
            return await _dal.UpdateCaChe();
        }

        #endregion

        #region 重写根据条件查询分页数据
        /// <summary>
        ///     重写根据条件查询分页数据
        /// </summary>
        /// <param name="predicate">判断集合</param>
        /// <param name="orderByType">排序方式</param>
        /// <param name="pageIndex">当前页面索引</param>
        /// <param name="pageSize">分布大小</param>
        /// <param name="orderByExpression"></param>
        /// <param name="blUseNoLock">是否使用WITH(NOLOCK)</param>
        /// <returns></returns>
        public new async Task<IPageList<PatientEntity>> QueryPageAsync(Expression<Func<PatientEntity, bool>> predicate,
            Expression<Func<PatientEntity, object>> orderByExpression, OrderByType orderByType, int pageIndex = 1,
            int pageSize = 20, bool blUseNoLock = false)
        {
            return await _dal.QueryPageAsync(predicate, orderByExpression, orderByType, pageIndex, pageSize, blUseNoLock);
        }
        #endregion

        #region 过滤传参生成执行where
        /// <summary>
        /// 过滤传参生成执行where
        /// </summary>
        /// <param name="Request">HttpRequest请求</param>
        /// <returns></returns>
        public Expression<Func<PatientEntity, bool>> ListFilter(HttpRequest Request)
        {
            var where = PredicateBuilder.True<PatientEntity>();
            if (Request.Form != null)
            {
                if (!Request.Form["Id"].IsEmpty())
                {
                    var Id = Request.Form["Id"].FirstOrDefault().ToString();
                    where = where.And(p => p.Id == Id);
                }
            }

            where = where.And(p => p.DeleteMark == 0);
            return where;
        }

        /// <summary>
        /// 过滤传参生成执行where
        /// </summary>
        /// <param name="param">传参JSON</param>
        /// <returns></returns>
        public Expression<Func<PatientEntity, bool>> ListFilter(string param)
        {
            var where = PredicateBuilder.True<PatientEntity>();
            if (!param.IsEmpty())
            {
                var queryParam = param.ToJObject();

                if (!queryParam["Id"].IsEmpty())
                {
                    var Id = queryParam["Id"].FirstOrDefault().ToString();
                    where = where.And(p => p.Id == Id);
                }
            }

            where = where.And(p => p.DeleteMark == 0);
            return where;
        }
        #endregion
    }
}
